<?php
$timezone = "Asia/Manila";

if(function_exists('date_default_timezone_set')) date_default_timezone_set($timezone);
//include 'C:\wamp\www\Projects\eformalistics\Formalistics\index.php'; // PROD
//include 'J:\eformalistics\Formalistics\index.php'; //TEST SERVER
include 'C:\wamp\www\Projects\eformalistics\Formalistics\index.php';
$br_line = "\r\n";
$updated_fields = 0;
$updated_fields_log = "";
$print_LOGS = "";
$print_LOGS .= print_r($br_line.$br_line."========================START MIDDLE WARE=======================================".$br_line.$br_line,true);
$db = new Database();

// Get All Forms
$forms = $db->query("SELECT
                    id,
                    form_json,form_table_name,form_name, active_fields, company_id
                    FROM tb_workspace","array");

foreach($forms as $form){
    
    $form_id = $form['id'];
    $form_table_name = $form['form_table_name'];
    $form_name = $form['form_name'];
    $form_json = $form['form_json'];
    $decode_form_json = json_decode($form_json,true);
    $middleware_formula = $decode_form_json['middleware'];
    $form_active_fields = $form['active_fields'];
    $GLOBALS['company_id'] = $form['company_id'];
    
    //
    $split_form_active_fields = split(",",$form_active_fields);
    if(count($middleware_formula) >= 1){
        $getRequest = $db->query("SELECT * FROM " . $form_table_name,"array");
        $print_LOGS .= print_r($br_line."TABLE NAME: ".$form_table_name.$br_line,true);
        print_r($br_line."TABLE NAME: ".$form_table_name.$br_line);
        foreach($getRequest as $request){
            $array_update = array();
            $AddDataSequence = array();
            
            if(array_key_exists("middleware_process",$request) ){
                if(floatval($request["middleware_process"]) >= 2){
                    $print_LOGS .= print_r($br_line."Skip process for TrackNo: ".$request["TrackNo"].", already processed!".$br_line,true);
                    continue;
                }
            }else{
                $print_LOGS .= print_r($br_line."Skip process, column middleware_process not existing!!".$br_line,true);
                continue;
            }

            try {
                foreach($split_form_active_fields as $fields){
                    foreach($middleware_formula as $key => $formula){
                        if($fields == $formula['FieldName'] ){
                            $print_LOGS .= print_r($br_line.">>START FIELD PROCESS AT TrackNo: ".$request["TrackNo"].$br_line,true);
                            if(array_key_exists("MiddlewareExecutionTag",$formula) ){

                                if(!empty($formula["MiddlewareExecutionTag"])){
                                    $formulaDoc_tag = new Formula($formula["MiddlewareExecutionTag"]);
                                    $formulaDoc_tag->DataFormSource[0] = $request;
                                    $execution_status = $formulaDoc_tag->evaluate();
                                    $print_LOGS .= print_r($br_line."-EVALUATING MiddlewareExecutionTag FORMULA FOR: ".$formula['FieldName']." AT TrackNo: ".$request["TrackNo"].$br_line,true);
                                    $print_LOGS .= print_r($br_line."----MiddlewareExecutionTag FORMULA: ".$formula["MiddlewareExecutionTag"].$br_line,true);
                                    $print_LOGS .= print_r($br_line."----MiddlewareExecutionTag PROCESSED FORMULA: ".$formulaDoc_tag->replaceFormulaFieldNames().$br_line,true);
                                    $print_LOGS .= print_r($br_line."----MiddlewareExecutionTag EVALUATED FORMULA: ".(($execution_status)?"true":"false").$br_line,true);
                                }else{
                                    $execution_status = true;
                                }
                            }else{
                                $execution_status = true;
                            }

                            if($execution_status){
                                $print_LOGS .= print_r($br_line."---EVALUATING MIDDLE WARE FORMULA FOR FIELD ".$formula['FieldName']." AT TrackNo: ".$request["TrackNo"]."  middleware_process == ".floatval($request["middleware_process"]).$br_line,true);
                                $formulaDoc = new Formula($formula["Formula"]);
                                $formulaDoc->DataFormSource[0] = $request;
                                foreach($AddDataSequence as $key => $val){
                                    $formulaDoc->updateDataFormSource($key, $val);
                                }
                                $array_update[$fields] = $formulaDoc->evaluate();
                                $request[$fields] = $formulaDoc->evaluate();
                                $AddDataSequence[$fields] = $formulaDoc->evaluate();
                                $formulaDoc->updateDataFormSource($fields,$formulaDoc->evaluate());


                                $print_LOGS .= print_r($br_line."------FORMULA:  ".$formula["Formula"].$br_line,true);
                                $print_LOGS .= print_r($br_line."------PROCCESSED FORMULA:  ".$formulaDoc->replaceFormulaFieldNames().$br_line,true);
                                $print_LOGS .= print_r($br_line."------EVALUATED FORMULA:  ".$request[$fields].$br_line,true);
                                $print_LOGS .= print_r($br_line."------RESULT:  ".$fields." = ".$request[$fields].$br_line,true);

                                print_r($br_line."FIELD: ".$formula['FieldName'].",  TRACKNO: ".$request["TrackNo"].$br_line);
                                print_r($br_line."------FORMULA:  ".$formula["Formula"].$br_line);
                                print_r($br_line."------PROCCESSED FORMULA:  ".$formulaDoc->replaceFormulaFieldNames().$br_line);
                                print_r($br_line."------EVALUATED FORMULA:  ".$request[$fields].$br_line);
                                print_r($br_line."------RESULT:  ".$fields." = ".$request[$fields].$br_line);
                            }else{
                                $print_LOGS .= print_r($br_line."MiddlewareExecutionTag Failed for field ".$formula['FieldName']." ".$br_line,true);
                                $print_LOGS .= print_r($br_line."----MiddlewareExecutionTag FORMULA: ".$formula["MiddlewareExecutionTag"].$br_line,true);
                                $print_LOGS .= print_r($br_line."----MiddlewareExecutionTag PROCESSED FORMULA: ".$formulaDoc_tag->replaceFormulaFieldNames().$br_line,true);
                                $print_LOGS .= print_r($br_line."----MiddlewareExecutionTag EVALUATED FORMULA: ".(($execution_status)?"true":"false").$br_line,true);
                            }
                        }
                    }
                }
                if(array_key_exists("middleware_process",$request) ){
                    $array_update["middleware_process"] = $request["middleware_process"];
                    $array_update["middleware_process"] = floatVal($array_update["middleware_process"]) + 1;
                }
                $print_LOGS .= print_r($br_line."<<END FIELD PROCESS AT TrackNo: ".$request["TrackNo"]." middleware_process == ".floatval($array_update["middleware_process"]).$br_line,true);
                
                // $print_LOGS .= print_r($br_line."REQUEST".$br_line.$br_line,true);
                // $print_LOGS .= print_r($request,true);
                // $print_LOGS .= print_r($br_line.$br_line."ARRAY UPDATE".$br_line.$br_line,true);
                // $print_LOGS .= print_r($array_update,true);
                // $print_LOGS .= print_r($br_line.$br_line,true);

                print_r($br_line."REQUEST".$br_line.$br_line);
                print_r($request);
                print_r($br_line."ARRAY UPDATE".$br_line.$br_line);
                print_r($array_update);
                print_r($br_line.$br_line);

                $update_record = $db->update($form_table_name, $array_update , array("ID"=>$request["ID"]));
                $updated_fields = $updated_fields + floatval($update_record);
                if(floatval($update_record) >= 1){
                    $updated_fields_log .=  $br_line.print_r($array_update,true).$br_line;
                }
            } catch (Exception $e) {
                $print_LOGS .= print_r($br_line.$e.$br_line,true);
            }
        }
    }else{
        continue;
    }
}
$print_LOGS .= print_r($br_line,true);
$print_LOGS .= print_r("UPDATED FIELDS: ".$updated_fields.$br_line.$br_line,true);
$print_LOGS .= print_r($updated_fields_log,true);
$print_LOGS .= print_r($br_line.$br_line,true);
if(floatval($updated_fields) >= 1){
	file_put_contents("C:\Users\Administrator\Desktop\copy\Middleware_LOG\middleware_bat_log_file (".date("Y-m-d H_i_s").") .txt",$print_LOGS);
}

?>